﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Security.Cryptography;
using System.Security.Cryptography;

namespace PSE.Deployment.Util
{
    public static class EncryptDecrypt
    {
        internal static byte[] CryptographyKey = { 15, 54, 6, 17, 38, 25, 80, 41 };

        public static string Encrypt(string value)
        {
            return Encrypt(value, CryptographyKey); 
        }

        public static string Encrypt(string value, byte[] key)
        {
            if (value == null)
                throw new ArgumentNullException("value");

            if (key == null)
                throw new ArgumentNullException("key");

            byte[] maskedString = null;
            byte[] unmaskedString = null;

            ProtectedKey protectedKey = ProtectedKey.CreateFromPlaintextKey(key, DataProtectionScope.LocalMachine);

            SymmetricCryptographer cryptographer = new SymmetricCryptographer(typeof(DESCryptoServiceProvider), protectedKey);
            
            unmaskedString = Encoding.Unicode.GetBytes(value);

            maskedString = cryptographer.Encrypt(unmaskedString);

            return Convert.ToBase64String(maskedString);
        }

        public static string Decrypt(string value)
        {
            return Decrypt(value, CryptographyKey);
        }

        public static string Decrypt(string value, byte[] key)
        {
            if (value == null)
                throw new ArgumentNullException("value");

            if (key == null)
                throw new ArgumentNullException("key");

            byte[] maskedString = null;
            byte[] unmaskedString = null;

            ProtectedKey protectedKey = ProtectedKey.CreateFromPlaintextKey(key, DataProtectionScope.LocalMachine);

            SymmetricCryptographer cryptographer = new SymmetricCryptographer(typeof(DESCryptoServiceProvider), protectedKey);

            maskedString = Convert.FromBase64String(value);

            unmaskedString = cryptographer.Decrypt(maskedString);

            return Encoding.Unicode.GetString(unmaskedString);
        }
    }
}